﻿using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nop.Services.Helpers
{
    public static class BlobStorageHelper
    {
        public static CloudBlobClient GetBlobClient(string connectionString)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            return blobClient;
        }

        public static CloudBlobContainer GetContainer(CloudBlobClient client, string containerName)
        {
            return client.GetContainerReference(containerName);
        }

        public static CloudBlockBlob GetBlockBlob(CloudBlobContainer container, string fileName)
        {
            if (container.Exists())
                return container.GetBlockBlobReference(fileName);
            else
                return null;
        }

        public static CloudBlobDirectory GetBlobDirectory(CloudBlobContainer container, string dirName)
        {
            return container.GetDirectoryReference(dirName);
        }

        public static byte[] GetBlobBytes(CloudBlobContainer container, string fileName)
        {
            var blob = GetBlockBlob(container, fileName);
            if (blob.Exists())
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    blob.DownloadToStream(stream);
                    stream.Seek(0, SeekOrigin.Begin);
                    return stream.ToArray();
                }
            }
            return new byte[0];
        }

        public static void CopyLocalFileToBlobStorage(CloudBlobContainer container, byte[] bytes, string fileName, string directory = null)
        {
            if (!container.Exists())
            {
                container.CreateIfNotExists();
            }
            
            if(!string.IsNullOrEmpty(directory))
            {
                fileName = directory+"/"+fileName;
            }

            var blogRef = container.GetBlockBlobReference(fileName);
            if (!blogRef.Exists())
            {
                blogRef.UploadFromByteArray(bytes, 0, bytes.Length);
            }
            
        }
    }
}
